package com.shenzhenai.migrationcodelab

import android.os.Bundle
import android.text.SpannedString
import android.text.method.LinkMovementMethod
import android.util.Log
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.text.HtmlCompat
import com.google.android.material.composethemeadapter.MdcTheme
import com.shenzhenai.migrationcodelab.databinding.MainAcBinding
import kotlin.random.Random

/**
 * @author huangzehui
 * @date 9/9/2025 下午11:09 周二
 * @description
 */
class MainAc : ComponentActivity() {

    private val mBinding by lazy {
        MainAcBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBinding.root)

        // xml 中使用 compose 的案例
        mBinding.composeView.setContent {
//            MdcTheme(context=this@MainAc) {
            desc()
//            }

        }
    }


    @Composable
    fun desc() {
        Surface {
            Column(
                modifier = Modifier
                    .padding(dimensionResource(id = R.dimen.margin_small))
            ) {
                PlantName(name = "水仙花${Random.nextInt()}")
                PlantWatering(
                    wateringInterval = 100, modifier = Modifier // 设置子视图垂直居中
                        .align(Alignment.CenterHorizontally)
                )
                PlantDescription(
                    description = "洪水未到先築堤，豺狼未來先磨刀。\n" +
                            "\n" +
                            "野狼臥在草地上，不斷勤奮地磨牙。\n" +
                            "\n" +
                            "狐狸看見了，便對牠說：「天氣這麼好，大家都在休息玩樂，你何不也加入我們呢？再說，森林裡一片寧靜，獵人和獵狗早已回家，老虎也不在附近徘徊，根本沒有危險，你為什麼還要這麼賣力磨牙呢？」\n" +
                            "\n" +
                            "野狼停下動作，回答說：「我磨牙可不是為了消遣。你想想，若有一天我被獵人或老虎追逐，那時才想磨牙豈不是太遲？平日先將牙齒磨好，到時才能保護自己啊！」\n" +
                            "\n" +
                            "這故事告訴我們：凡事應當未雨綢繆，居安思危，這樣當危險突然降臨時，才不至於手忙腳亂。\n" +
                            "\n" +
                            "俗話說：「書到用時方恨少。」如果平常不努力充實學問，臨時抱佛腳往往來不及。\n" +
                            "\n" +
                            "有些人常抱怨缺乏機會，但等到升遷機會真正來臨，才發現自己平日沒有累積足夠的學識與能力，結果無法勝任，只能徒留遺憾。<a href='https://www.baidu.com'>百度</a>\n" +
                            "洪水未到先築堤，豺狼未來先磨刀。\n" +
                            "\n" +
                            "野狼臥在草地上，不斷勤奮地磨牙。\n" +
                            "\n" +
                            "狐狸看見了，便對牠說：「天氣這麼好，大家都在休息玩樂，你何不也加入我們呢？再說，森林裡一片寧靜，獵人和獵狗早已回家，老虎也不在附近徘徊，根本沒有危險，你為什麼還要這麼賣力磨牙呢？」\n" +
                            "\n" +
                            "野狼停下動作，回答說：「我磨牙可不是為了消遣。你想想，若有一天我被獵人或老虎追逐，那時才想磨牙豈不是太遲？平日先將牙齒磨好，到時才能保護自己啊！」\n" +
                            "\n" +
                            "這故事告訴我們：凡事應當未雨綢繆，居安思危，這樣當危險突然降臨時，才不至於手忙腳亂。\n" +
                            "\n" +
                            "俗話說：「書到用時方恨少。」如果平常不努力充實學問，臨時抱佛腳往往來不及。\n" +
                            "\n" +
                            "有些人常抱怨缺乏機會，但等到升遷機會真正來臨，才發現自己平日沒有累積足夠的學識與能力，結果無法勝任，只能徒留遺憾。<a href='https://www.baidu.com'>百度</a>"
                )

                weijueyeTest()

            }
        }
    }

    @Composable
    fun weijueyeTest() {
        // 韦爵爷部分代码
        // 可点击文本
        // https://www.bilibili.com/video/BV1e5411o76A?vd_source=e07cc8cc94eb22bd76722071b03cd199&spm_id_from=333.788.videopod.sections
        ClickableText(text = buildAnnotatedString {
            // 这里类似 SpannedString
            append("Hello World")

            withStyle(
                style = SpanStyle(
                    color = Color.Red,
                    textDecoration = TextDecoration.Underline,
                    fontSize = 16.sp
                )
            ) {
                append("Jetpack Compose")
            }
        }) {
            // it 是标识点击的字符串的角标
            Log.e("young_test9090d", "it = ${it}")
        }

        // 可选择容器，就是可以选中文本，进行复制
        SelectionContainer {
            Text("Hello World")
        }

        // https://www.bilibili.com/video/BV1e5411o76A?vd_source=e07cc8cc94eb22bd76722071b03cd199&spm_id_from=333.788.videopod.sections
        val annotatedString = buildAnnotatedString {
            append("点击登录即代表您已知悉和同意")

            /**
             * pushStringAnnotation 和 pop 圈着的区域，都可以获取到 pushStringAnnotation 的参数；
             *
             * pushStringAnnotation 就是传入参数，然后直到调用 pop 之前到文本，都可以获取到 pushStringAnnotation 的参数
             */

            pushStringAnnotation("protocol", "https://www.baidu.com")
            withStyle(
                style = SpanStyle(
                    color = Color.Blue,
                    textDecoration = TextDecoration.Underline
                )
            ) {
                append("用户协议")
            }
            pop()

            append("和")

            pushStringAnnotation("privacy", "https://www.google.com/")
            withStyle(
                style = SpanStyle(
                    color = Color.Blue,
                    textDecoration = TextDecoration.Underline
                )
            ) {
                append("隐私政策")
            }
            pop()

        }

        ClickableText(text = annotatedString) { offset ->
            // 获取 pushStringAnnotation 的参数
            annotatedString.getStringAnnotations("protocol", start = offset, end = offset)
                .firstOrNull()?.let { annotation ->
                    Log.e("young_test9090d", "点击了用户协议 = ${annotation.item}")
                }

            annotatedString.getStringAnnotations("privacy", start = offset, end = offset)
                .firstOrNull()?.let { annotation ->
                    Log.e("young_test9090d", "点击了隐私政策 = ${annotation.item}")
                }


        }
    }


    @Composable
    fun PlantName(name: String) {
        Text(
            text = name,
            style = MaterialTheme.typography.titleMedium,
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = dimensionResource(id = R.dimen.margin_small))
                .wrapContentWidth(Alignment.CenterHorizontally)
        )
    }


    @Composable
    fun PlantWatering(wateringInterval: Int, modifier: Modifier = Modifier) {
        val centerWithPaddingModifier = modifier
            .padding(horizontal = dimensionResource(R.dimen.margin_small))

        val normalPadding = dimensionResource(R.dimen.margin_normal)
        Text(
            text = stringResource(R.string.watering_needs_prefix),
            color = MaterialTheme.colorScheme.primary,
            fontWeight = FontWeight.Bold,
            modifier = centerWithPaddingModifier.padding(top = normalPadding)
        )

        val wateringInterValText = LocalContext.current.resources.getQuantityString(
            R.plurals.watering_needs_suffix, wateringInterval, wateringInterval
        )

        Text(
            text = wateringInterValText,
            modifier = centerWithPaddingModifier.padding(bottom = normalPadding)
        )

    }

    @Composable
    fun PlantDescription(description: String) {
        val htmlDescription = remember(description) {
            // 使用 HtmlCompat.fromHtml 是做过兼容的 html
            HtmlCompat.fromHtml(description, HtmlCompat.FROM_HTML_MODE_COMPACT)
        }
        AndroidView(
            factory = { context ->
                TextView(context).apply {
                    // 设置 TextView 为可点击
                    movementMethod = LinkMovementMethod.getInstance()
                }
            },
            update = {
                it.text = htmlDescription
            })
    }

}